package com.cnpc.netty.transfer;

import java.util.concurrent.TimeUnit;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.EventLoop;

/**
 * 负责监听启动时连接失败（例如：tcp server还未启动），重新连接功能
 *
 */
public class ConnectionListener implements ChannelFutureListener {

	private final TcpConnection imConnection = new TcpConnection();

	@Override
	public void operationComplete(ChannelFuture channelFuture) throws Exception {
		if (!channelFuture.isSuccess()) {
			System.err.println("服务端链接失败,进行重连...");
			final EventLoop loop = channelFuture.channel().eventLoop();
			loop.schedule(new Runnable() {
				@Override
				public void run() {
					System.err.println("服务端链接不上，开始重连操作...");
					imConnection.connect(Transfer.tcpip, Transfer.tcpport);
				}
			}, 1L, TimeUnit.SECONDS);
		} else {
			System.err.println("服务端链接成功...");
		}
	}
}